package com.xh.model.response;

import cn.hutool.json.JSONUtil;
import com.xh.model.dto.PosterDTO;
import com.xh.model.dto.PosterItemDTO;
import com.xh.model.enums.MessageEnum;
import com.xh.model.request.Editor;
import com.xh.model.table.Poster;
import com.xh.model.table.PosterItem;
import lombok.*;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class PosterResponse {

    private int code;

    private String msg;

    private List<Posters> posters;

    public static PosterResponse ok(List<Posters> posters) {
        return PosterResponse.builder()
                .code(MessageEnum.SUCCESS.getCode())
                .msg(MessageEnum.SUCCESS.getMsg())
                .posters(posters).build();
    }

    /**
     * 构建响应数据
     */
    public static List<Posters> build(List<Poster> posters, Map<Long, List<PosterItem>> groupMap) {
        return posters.stream().map(item -> {
            Posters poster = new Posters();
            poster.setId(item.getId());
            poster.setCode("UUID");
            poster.setName(item.getName());
            poster.setPreview(item.getBgUrl());
            poster.setCreateTime(item.getCreateTime());
            poster.setUpdateTime(item.getUpdateTime());

            List<PosterItem> posterItems = groupMap.get(item.getId());
            PosterDTO posterDTO = new PosterDTO();
            BeanUtils.copyProperties(item, posterDTO);
            posterDTO.setEditor(JSONUtil.toBean(item.getEditor(), Editor.class));
            posterDTO.setItems(PosterItemDTO.convert(posterItems));
            poster.setJson(JSONUtil.toJsonStr(posterDTO));
            return poster;
        }).collect(Collectors.toList());
    }
}
